package com.tanhua.dubbo.server.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tanhua.dubbo.server.config.HuanXinConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class TokenService {
    @Autowired
    private HuanXinConfig huanXinConfig;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    //为token自定义一个redisKey
    private static final String REDIS_KEY = "HX_TOKEN";

    /**
     * 1.获取token,首先去redis中去找
     * 1.1找到直接返回token
     * 1.2找不到就要去环信屏重新请求token
     * 2.在环信中获得到token后,需要再将token写到redis中
     *
     * @return
     */
    public String getToken() {
        String token = redisTemplate.opsForValue().get(REDIS_KEY);
        if (StrUtil.isNotEmpty(token)) {
            return token;
        }
        return refreshToken();
    }

    public String refreshToken() {
        //1.构建请求token的url
        String targetUrl = huanXinConfig.getUrl() + huanXinConfig.getOrgName() + "/"
                + huanXinConfig.getAppName() + "/token";
        //2.使用hashMap构建请求体
        Map<String, Object> param = new HashMap<>();
        param.put("grant_type", "client_credentials");
        param.put("client_id", huanXinConfig.getClientId());
        param.put("client_secret", huanXinConfig.getClientSecret());
        //3.利用糊涂工具发送请求
        /**
         * 注:这里的body需要的是json类型的数据
         *        时间的单位是秒
         */
        HttpResponse response = HttpRequest.post(targetUrl)
                .body(JSONUtil.toJsonStr(param))
                .timeout(20000).execute();
        if (!response.isOk()) {
            log.error("token刷新错误!");
            return null;
        }
        String jsonBody = response.body();
        JSONObject jsonObject = JSONUtil.parseObj(jsonBody);
        String token = jsonObject.getStr("access_token");
        if (StrUtil.isNotEmpty(token)) {
            //如果token不为空,需要将token存入redis中,且设置token在redis中的有效时间<token在环信中的有效时间
            Long aLong = jsonObject.getLong("expires_in") - 3600;//提前一小时
            redisTemplate.opsForValue().set(REDIS_KEY, token, aLong, TimeUnit.SECONDS);
            return token;
        }
        return null;
    }
}
